package com.jjlin.chapter_2;

import java.util.*;
public class CD139{
    public static class Node{
        public int val;
        public Node next;
        public Node(int data){
            this.val = data;
        }
    }

    public static Node createNodeList(int[] nums){
        if(nums == null || nums.length < 1)
            return null;
        Node head = new Node(nums[0]);
        Node pre = head;
        for(int i = 1; i < nums.length; i++){
            Node cur = new Node(nums[i]);
            pre.next = cur;
            pre = cur;
        }
        return head;
    }

    public static void printNodeList(Node head){
        Node cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    //单链表的选择排序
    public static Node selectSort(Node head){
        if(head == null || head.next == null)
            return head;
        Node cur = head;
        Node smallPre = null;
        Node small = null;
        Node tail = null;
        while(cur != null){
            small = cur;
            smallPre = getSmallestPreNode(small);
            if(smallPre != null){//获取最小节点small
                small = smallPre.next;
                smallPre.next = small.next;
            }
            cur = cur == small ? cur.next : cur;//更新cur指针
            if(tail == null){
                head = small;
            }else{
                tail.next = small;//连接small节点
            }
            tail = small;//更新tail
        }
        return head;
    }

    //获取最小节点的前一个节点，如果head为最小节点，则返回null
    public static Node getSmallestPreNode(Node head){
        Node cur = head.next;
        Node pre = head;
        Node smallPre = null;
        Node small = head;
        while(cur != null){
            if(cur.val < small.val){
                small = cur;
                smallPre = pre;
            }
            pre = cur;
            cur = cur.next;
        }
        return smallPre;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n; i++)
            nums[i] = sc.nextInt();
        Node head = createNodeList(nums);
        head = selectSort(head);
        printNodeList(head);
    }
}


